var console = console;

homeApp.controller('dropdownController', ['$scope', '$http', '$modal', function ($scope, $http, $modal) {
    'use strict';
    
    $scope.templatePopUp = function(templateURL, templateController, templateWindowClass, templateSize, templateParams) {
        return $modal.open({
            templateUrl     : templateURL,
            controller      : templateController,
            backdropClass   : 'bacdropAdditionClass',
            windowClass     : templateWindowClass,
            size            : templateSize,
            resolve: {
                params : function () {
                    return templateParams;
                }
            }
        });
    }
    
    $scope.clickaccount = function () {
        var modalInstance = $scope.templatePopUp('accountPopUp.html', 'PopUpAccountController', 'accountmodalclass', null, $scope.templatePopUp);
        
        modalInstance.result.then(function (report) {
            if (report === 'Add User') {
                $scope.clicknewuser();
            }
        }, function () {

        });
    };
    
    $scope.clickpassword = function () {
        var modalInstance = $scope.templatePopUp('passwordPopUp.html', 'PopUpPasswordController', 'passwordmodalclass','sm', null);
        
        modalInstance.result.then(function () {
            $scope.createNotification("Password successfully changed.");
        }, function () {
            
        });
    };
    
    $scope.clicklogout = function () {
        window.location.href = 'logout';
    };
    
    $scope.createNotification = function (message) {
        var modalInstance = $scope.templatePopUp('notificationPopUp.html', 'NotificationController', 'notificationmodalclass', 'sm', message);
    }
    
    $scope.newuserNotification = function (message) {
        var modalInstance = $scope.templatePopUp('notificationPopUp.html', 'NotificationController', 'notificationmodalclass', 'sm', message);
        
        modalInstance.result.then(function () {
            $scope.clickaccount();
        }, function () {
            $scope.clickaccount();
        });
    }
    
    $scope.clicknewuser = function () {
        var modalInstance = $scope.templatePopUp('newuserPopUp.html', 'newuserController', 'newusermodalclass', 'sm', null);
        
        modalInstance.result.then(function (username) {
            if (typeof (username) !== 'undefined') {
                $scope.newuserNotification('Account ' + username + ' has been created');
            } else {
                $scope.clickaccount();
            }
        }, function () {
            $scope.clickaccount();
        });
    }
    
    $scope.checkUser = function(some) {
        //console.log(some);
        if ((some === 'admin') || (some === 'Admin')) {
            return true;
        } else {
            return false;   
        }
    }
}]);

homeApp.controller('PopUpAccountController',['$scope','$modal','$modalInstance','$http', 'params', function($scope,$modal,$modalInstance,$http, params) {
    $scope.maxSize          = 3;
    $scope.bigCurrentPage   = 1;
    
    $scope.totalstreams     = 5;
    
    $scope.nodata           = true;
    $scope.loading          = true;
    $http.get('api/users')
        .success(function (data) {
            if (data.response === "OK" && data.message === "Get all users data success.") {
                $scope.nodata        = false;
                
                $scope.datamember    = _.sortBy(data.result.users, function(some){ return some.username; });
                
                $scope.streams       = $scope.datamember.slice(0, $scope.totalstreams);
                //console.log(data.result.users);
            } else {
                console.log(data);
            }
            $scope.loading = false;
        }).error(function (data) {
            $scope.loading = false;
            console.log(data);
        });

    $scope.$watch('bigCurrentPage', function (newVal, oldVal) {
        if ((newVal !== oldVal) && (typeof(newVal) !== 'undefined') && (typeof(oldVal) !== 'undefined')) {
            //console.log($scope.bigCurrentPage);
            $scope.streams              = $scope.datagangguan.slice(($scope.bigCurrentPage - 1) * $scope.totalstreams, $scope.bigCurrentPage * $scope.totalstreams);
        }
    });
    
    $scope.ok = function () {
        $modalInstance.close();
    };
    
    $scope.editingRole = function(some) {
        some.current  = some.role;
        some.isEdit   = true;
        some.disabled = false;
    }
    
    $scope.doneEditing = function(some) {
        some.disabled = true;
        $http.get('api/updateuser',{params:{username: some.username, role: some.role}})
            .success(function (data) {
                //console.log(data);
                if (data.response === "OK" && data.status_code == 200) {
                    some.isEdit  = false;
                } else {

                }
            }).error(function (data) {
                console.log(data);
            }); // */
    }
    
    $scope.cancelEditing = function(some) {
        some.isEdit  = false;
        some.role = some.current;
    }
    
    $scope.addnewuserclick = function() {
        $modalInstance.close('Add User');
    }
    
    $scope.removeuserclick = function(some) {
        var anotherModalInstance = params('AnotherDeletePopUp.html', 'deleteuserController', 'windowAdditionClass', 'sm', some);
        
        anotherModalInstance.result.then(function (username) {
            if (typeof (username) !== 'undefined') {
                $scope.streams = _.reject($scope.streams, function(stream) {
                    return (stream.username == username);
                });
            }
        }, function () {
            
        });
    }
}]);

homeApp.controller('PopUpPasswordController',['$scope','$modal','$modalInstance','$http','md5',function($scope,$modal,$modalInstance,$http,md5) {
    $scope.disabled = false;
    
    $scope.ok = function (username) {
        $scope.disabled = true;
        $scope.isError = false;
        
        if ((typeof ($scope.new_password) !== 'undefined') &&
           (typeof ($scope.current_password) !== 'undefined') &&
           (typeof ($scope.another_password) !== 'undefined')){
            if ($scope.new_password === $scope.another_password) {
                if ($scope.new_password === $scope.current_password) {
                    $scope.errormessage = 'New password is exactly the same as the old one.';
                    $scope.isError      = true;
                } else {
                    $http.get('api/login',{params:{username: username, password: md5.createHash($scope.current_password || '')}})
                        .success(function (data) {
                            //console.log(data);
                            if (data.response === "OK" && data.status_code == 200) {
                                $http.get('api/updateuser',{params:{username: username, password: md5.createHash($scope.new_password || '')}})
                                    .success(function (data) {
                                        //console.log(data);
                                        if (data.response === "OK" && data.status_code == 200) {
                                            $modalInstance.close();
                                        } else {

                                        }
                                    }).error(function (data) {
                                        console.log(data);
                                    }); // */
                            } else {
                                $scope.errormessage = 'Wrong password, please input the password for this username : ' + username + '.';
                                $scope.isError      = true;
                            }
                        }).error(function (data) {
                            console.log(data);
                        }); // */
                }
            } else {
                $scope.errormessage = 'New password confirmation failed.';
                $scope.isError      = true;
            }
        }
    };

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };    
}]); 

homeApp.controller('NotificationController',['$scope','$modal','$modalInstance','$http','params',function($scope,$modal,$modalInstance,$http,params) {
    $scope.message = params;
    
    $scope.ok = function () {
        $modalInstance.close();
    };
}]);

homeApp.controller('newuserController',['$scope','$modal','$modalInstance','$http','md5', function($scope,$modal,$modalInstance,$http,md5) {
    $scope.disabled = false;
    
    $scope.ok = function() {
        $scope.disabled = true;
        if ((typeof ($scope.new_password) !== 'undefined') &&
       (typeof ($scope.new_username) !== 'undefined') &&
       (typeof ($scope.another_password) !== 'undefined')){
            if ($scope.new_password === $scope.another_password) {
                $http.get('api/register',{params:{username: $scope.new_username, password: md5.createHash($scope.new_password || ''), role: $scope.new_role}})
                    .success(function (data) {
                        //console.log(data);
                        if (data.response === "OK" && data.status_code == 200) {
                            $modalInstance.close($scope.new_username);
                        } else {

                        }
                    }).error(function (data) {
                        console.log(data);
                    }); // */
            } else {
                $scope.errormessage = 'New password confirmation failed.';
                $scope.isError      = true;
            }
        }
    }
    
    $scope.cancel = function() {
        $modalInstance.close();
    }
}]);

homeApp.controller('deleteuserController',['$scope','$modal','$modalInstance','$http','md5','params',function($scope,$modal,$modalInstance,$http,md5,params) {
    $scope.disabled = false;
    $scope.username = params.username;
    
    $scope.ok = function() {
        $scope.disabled = true;
        $http.get('api/deleteuser',{params:{username: $scope.username}})
            .success(function (data) {
                //console.log(data);
                if (data.response === "OK" && data.status_code == 200) {
                    $modalInstance.close($scope.username);
                } else {

                }
            }).error(function (data) {
                console.log(data);
            }); // */        
    }
    
    $scope.cancel = function() {
        $modalInstance.close();
    }
}]);
